
package pos.storage.db.mysql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;

/**
 * Selects the data from the database by executing a SQL and populates in a Table model
 * Source: http://www.java2s.com/Code/Java/Swing-JFC/ResultSetandJTable.htm
 * 
 */
public class SelectQueryTableModel extends AbstractTableModel{
    
    public Vector<String> colNameArray1 = new Vector<String>();
    Vector rows = new Vector();
    int colCount = 0;
        
    /**
     * Returns the row count
     * @return 
     */
    public int getRowCount(){
        if(rows == null){
            rows = new Vector();
        }
        return rows.size();
    }
    /**
     * 
     * @return 
     */
    public int getColumnCount(){
        return colCount;
    }
    public String getColumnName(int i) {
        return colNameArray1.get(i);
    }
    public Object getValueAt(int row, int column){
        Object[] rowObj = (Object[])rows.get(row);
        Object valObj = rowObj[column];
        return valObj;
    }
    
    public void setValueAt(int row, int column, Object valObj){
        Object[] rowObj = (Object[])rows.get(row);
        rowObj[column] = valObj;
    }
    public void removeAll(){
        rows.removeAllElements();
    }
    public void removeAt(int i){
        rows.remove(i);
    }
    public void addColumn(String colName){
        colNameArray1.add(colName);
        fireTableStructureChanged();
        fireTableChanged(null);
    }
    public void genTable(Connection con, String sql)throws SQLException{
        
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        ResultSetMetaData rmd = rs.getMetaData();
        colCount = rmd.getColumnCount();
        //colNameArray1 = new String[colCount];
        for(int i=0; i < colCount; i++){
            colNameArray1.add(rmd.getColumnName(i+1));
        }
        while(rs.next()){
            Object[] row = new Object[colCount];
            for(int i=0; i < colCount; i++){
                row[i] = rs.getObject(i+1);
            }
            rows.add(row);
        }
        fireTableChanged(null);
    }
}
